import { Injectable } from '@angular/core';
import { HttpClient, HttpHandler, HttpHeaders, HttpRequest } from '@angular/common/http';
import { Subject } from 'rxjs/Subject';
import { Router } from '@angular/router';
import { Jwt } from '../classes/jwt';
import { StorageService } from '../services/storage.service';
import { User } from '../classes/user';

@Injectable()
export class AccountService {
  constructor(private http: HttpClient, private storage: StorageService, private router: Router) { }
  public subjectSignin: Subject<string> = new Subject<string>();
  public subjectUser: Subject<User> = new Subject<User>();

  public Authorization =
    'Basic d2Vic2l0ZTo0NWRjZThhZmQ5YTQ3YWQzODFlNDEwZjEwMGUwYTc5ZTgxYWU3ZDA0ZDdjM2M4ZThhMzNkZTc1YzllN2QxZWQ5NzA4MDRlZjcyMTA5MjcxOA==';

  public signin(username: string, password: string): string {
    // Make the HTTP request: //<Page<Demand>> , { observe: 'response' | events } , { withCredentials: true }
    this.storage.remove('token');

    const formData = new FormData();
    formData.append('grant_type', 'password');
    formData.append('username', username);
    formData.append('password', password);

    this.http.post<Jwt>('/api/oauth/token', formData, {
      headers: new HttpHeaders().set('Authorization', this.Authorization),
    }).subscribe(res => {
      this.storage.set('token', res.access_token);
      this.router.navigate(['/index']);
    }, err => {
      this.subjectSignin.next('用户名或密码错误!');
    });
    return null;
  }

  public getSmsCaptcha(cellphone: string) {
    this.http.get('/api//account/captcha/sms/' + cellphone).subscribe(res => {
      return;
    }, err => {
      this.subjectSignin.next(err);
    });
  }

  public getUser() {
    this.http.get<User>('/api/account').subscribe(res => {
      this.subjectUser.next(res);
      return;
    }, err => {
      this.router.navigate(['/single/signin']);
    });
  }
}
